<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="pdf名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入pdf名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="乐器名称" prop="instrumentName">
        <el-input v-model="queryParams.instrumentName" placeholder="请输入乐器名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="作曲家名称" prop="composerName">
        <el-input v-model="queryParams.composerName" placeholder="请输入作曲家名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="合集名称" prop="collectionName">
        <el-input v-model="queryParams.collectionName" placeholder="请输入合集名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="出版社名称" prop="publishName">
        <el-input v-model="queryParams.publishName" placeholder="请输入出版社名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="出版信息名称" prop="publishInfoName">
        <el-input v-model="queryParams.publishInfoName" placeholder="请输入出版信息名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:pdf:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:pdf:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:pdf:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:pdf:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="pdfList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="pdf名称" align="center" prop="name" />
      <!-- 移除原有的pdf链接列 -->
      <el-table-column label="乐器" align="center" prop="instrumentName" />
      <el-table-column label="作曲家" align="center" prop="composerName" />
      <el-table-column label="合集" align="center" prop="collectionName" />
      <el-table-column label="出版社" align="center" prop="publishName" />
      <el-table-column label="出版信息" align="center" prop="publishInfoName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-link" @click="handleViewUrl(scope.row)">查看链接</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:pdf:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:pdf:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改pdf对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="pdf名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入pdf名称" />
        </el-form-item>
        <!-- <el-form-item label="pdf链接" prop="url">
          <el-input v-model="form.url" placeholder="请输入pdf链接" />
        </el-form-item> -->
        <el-form-item label="乐器" prop="instrumentId">
          <el-autocomplete v-model="form.instrumentName" :fetch-suggestions="queryInstrumentList" placeholder="请输入乐器名称"
            style="width: 100%" @select="handleInstrumentSelect" @focus="handleInstrumentFocus" clearable>
            <template slot-scope="{ item }">
              <div>{{ item.name }}</div>
            </template>
          </el-autocomplete>
        </el-form-item>
        <el-form-item label="作曲家" prop="composerId">
          <el-autocomplete v-model="form.composerName" :fetch-suggestions="queryComposerList" placeholder="请输入作曲家名称"
            style="width: 100%" @select="handleComposerSelect" @focus="handleComposerFocus" clearable>
            <template slot-scope="{ item }">
              <div>{{ item.name }}</div>
            </template>
          </el-autocomplete>
        </el-form-item>
        <el-form-item label="合集" prop="collectionId">
          <el-autocomplete v-model="form.collectionName" :fetch-suggestions="queryCollectionList" placeholder="请输入合集名称"
            style="width: 100%" @select="handleCollectionSelect" @focus="handleCollectionFocus" clearable>
            <template slot-scope="{ item }">
              <div>{{ item.name }}</div>
            </template>
          </el-autocomplete>
        </el-form-item>
        <el-form-item label="出版社" prop="publishId">
          <el-autocomplete v-model="form.publishName" :fetch-suggestions="queryPublishList" placeholder="请输入出版社名称"
            style="width: 100%" @select="handlePublishSelect" @focus="handlePublishFocus" clearable>
            <template slot-scope="{ item }">
              <div>{{ item.name }}</div>
            </template>
          </el-autocomplete>
        </el-form-item>
        <el-form-item label="出版社信息" prop="publishInfoId">
          <el-autocomplete v-model="form.publishInfoName" :fetch-suggestions="queryInfoList" placeholder="请输入出版社信息名称"
            style="width: 100%" @select="handleInfoSelect" @focus="handleInfoFocus" :disabled="!form.publishId"
            clearable>
            <template slot-scope="{ item }">
              <div>{{ item.name }}</div>
            </template>
          </el-autocomplete>
        </el-form-item>
        <el-form-item label="文件id" prop="files">

          <el-upload ref="upload" v-model="form.pdfFile" :limit="1" :on-change="handleFileChange"
            :on-remove="handleFileRemove" :before-upload="beforePdfUpload" class="upload-demo" drag action="#"
            :auto-upload="false" accept="application/pdf,.pdf">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传PDF文件</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 查看链接弹窗 -->
    <el-dialog title="PDF链接" :visible.sync="urlDialogVisible" width="500px" append-to-body>
      <div class="url-container">
        <a :href="currentUrl" target="_blank" class="pdf-link">{{ currentUrl }}</a>
        <el-button type="primary" icon="el-icon-document-copy" @click="copyUrl">复制链接</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listPdf, getPdf, delPdf, addPdf, updatePdf, listCollectionSelect,
  listComposerSelect,
  listInstrumentSelect,
  listPublishSelect,
  listInfoSelect
} from "@/api/system/pdf"

export default {
  name: "Pdf",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // pdf表格数据
      pdfList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 链接弹窗相关
      urlDialogVisible: false,
      currentUrl: "",
      // 查询参数
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        url: null,
        instrumentId: null,
        composerId: null,
        collectionId: null,
        publishId: null,
        publishInfoId: null,
        instrumentName: null,
        composerName: null,
        collectionName: null,
        publishName: null,
        publishInfoName: null,
        deleteFlag: '0'
      },
      // 表单参数
      form: {
        id: null,
        name: null,
        url: null,
        instrumentId: null,
        instrumentName: null,
        composerId: null,
        composerName: null,
        collectionId: null,
        collectionName: null,
        publishId: null,
        publishName: null,
        publishInfoId: null,
        publishInfoName: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        files: null
      },
      // 表单校验
      rules: {
      },
      // 下拉选项数据
      collectionOptions: [],
      composerOptions: [],
      instrumentOptions: [],
      publishOptions: [],
      infoOptions: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 移除原有的getSelectOptions方法

    /** 查询pdf列表 */
    getList() {
      this.loading = true
      listPdf(this.queryParams).then(response => {
        console.log(response.rows);
        this.pdfList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        url: null,
        instrumentId: null,
        instrumentName: null,
        composerId: null,
        composerName: null,
        collectionId: null,
        collectionName: null,
        publishId: null,
        publishName: null,
        publishInfoId: null,
        publishInfoName: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        files: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      // 确保名称字段也被重置
      this.queryParams.instrumentName = null;
      this.queryParams.composerName = null;
      this.queryParams.collectionName = null;
      this.queryParams.publishName = null;
      this.queryParams.publishInfoName = null;
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      console.log(this.form);

      this.reset()
      this.open = true
      this.title = "添加pdf"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getPdf(id).then(response => {
        console.log(response.data);
        this.form = response.data
        // 设置名称字段，用于显示
        this.form = response.data
        // this.form.instrumentName = response.data.instrumentName || ''
        // this.form.composerName = response.data.composerName || ''
        // this.form.collectionName = response.data.collectionName || ''
        // this.form.publishName = response.data.publishName || ''
        // this.form.publishInfoName = response.data.publishInfoName || ''
        this.open = true
        this.title = "修改pdf"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePdf(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            const formData = new FormData();
            // 添加基本表单字段
            if (this.form.name) formData.append('name', this.form.name);
            if (this.form.url) formData.append('url', this.form.url);
            if (this.form.instrumentId) formData.append('instrumentId', this.form.instrumentId);
            if (this.form.composerId) formData.append('composerId', this.form.composerId);
            if (this.form.collectionId) formData.append('collectionId', this.form.collectionId);
            if (this.form.publishId) formData.append('publishId', this.form.publishId);
            if (this.form.publishInfoId) formData.append('publishInfoId', this.form.publishInfoId);

            // 处理文件上传
            if (this.form.files) {
              formData.append('files', this.form.files);
              console.log('添加文件到表单:', this.form.files.name);
            }

            // 不传递第二个参数
            addPdf(formData).then(response => {
              console.log('上传响应:', response);
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            }).catch(error => {
              console.error('上传失败:', error);
              this.$modal.msgError("上传失败: " + (error.message || '未知错误'));
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除pdf编号为"' + ids + '"的数据项？').then(function () {
        return delPdf(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => { })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/pdf/export', {
        ...this.queryParams
      }, `pdf_${new Date().getTime()}.xlsx`)
    },
    handleFileChange(file, fileList) {
      // 保存整个文件列表
      this.form.files = file.raw;
    },

    handleFileRemove(file, fileList) {
      // 更新删除后的文件列表
      this.form.files = file;
    },

    /** PDF文件上传前的校验 */
    beforePdfUpload(file) {
      // 检查文件类型
      const isPDF = file.type === 'application/pdf';
      // 检查文件扩展名（作为备用验证）
      const isValidExtension = file.name.toLowerCase().endsWith('.pdf');

      if (!isPDF || !isValidExtension) {
        this.$message.error('只能上传PDF文件!');
        return false;
      }

      // 检查文件大小，限制为20MB
      const isLt20M = file.size / 1024 / 1024 < 20;
      if (!isLt20M) {
        this.$message.error('PDF文件大小不能超过20MB!');
        return false;
      }

      return true;
    },
    // 处理出版社选择变化
    handlePublishChange(val) {
      // 将parentId的值同步到publishId
      this.form.publishId = val;
      if (val) {
        // 根据选中的出版社ID获取对应的出版信息
        listInfoSelect(val).then(response => {
          this.infoOptions = response.data;
        });
      } else {
        // 如果未选择出版社，清空出版信息选项
        this.infoOptions = [];
        this.form.publishInfoId = null;
      }
    },



    /** 查看链接按钮操作 */
    handleViewUrl(row) {
      console.log(row);
      this.currentUrl = row.url;
      this.urlDialogVisible = true;
    },

    /** 复制链接到剪贴板 */
    copyUrl() {
      // 创建一个临时的textarea元素
      const textarea = document.createElement('textarea');
      textarea.value = this.currentUrl;
      document.body.appendChild(textarea);

      // 选择文本并复制
      textarea.select();
      document.execCommand('copy');

      // 移除临时元素
      document.body.removeChild(textarea);

      // 提示用户
      this.$message({
        message: '链接已复制到剪贴板',
        type: 'success'
      });
    },

    // 乐器模糊查询
    queryInstrumentList(queryString, cb) {
      // 如果queryString是null，则使用空字符串代替
      const query = queryString === null ? '' : queryString;
      listInstrumentSelect(query).then(response => {
        cb(response.data || []);
      });
    },

    // 作曲家模糊查询
    queryComposerList(queryString, cb) {
      const query = queryString === null ? '' : queryString;
      listComposerSelect(query).then(response => {
        cb(response.data || []);
      });
    },

    // 合集模糊查询
    queryCollectionList(queryString, cb) {
      const query = queryString === null ? '' : queryString;
      listCollectionSelect(query).then(response => {
        cb(response.data || []);
      });
    },

    // 出版社模糊查询
    queryPublishList(queryString, cb) {
      const query = queryString === null ? '' : queryString;
      listPublishSelect(query).then(response => {
        cb(response.data || []);
      });
    },

    // 出版信息模糊查询
    queryInfoList(queryString, cb) {
      if (!this.form.publishId) {
        cb([]);
        return;
      }
      const query = queryString === null ? '' : queryString;
      listInfoSelect(this.form.publishId, query).then(response => {
        cb(response.data || []);
      });
    },

    // 焦点事件处理 - 获取全部列表
    handleInstrumentFocus() {
      // 直接调用查询方法，传入空字符串获取全部列表
      this.queryInstrumentList('', (data) => {
        // 自动处理下拉列表
      });
    },

    handleComposerFocus() {
      this.queryComposerList('', (data) => {
        // 自动处理下拉列表
      });
    },

    handleCollectionFocus() {
      this.queryCollectionList('', (data) => {
        // 自动处理下拉列表
      });
    },

    handlePublishFocus() {
      this.queryPublishList('', (data) => {
        // 自动处理下拉列表
      });
    },

    handleInfoFocus() {
      if (!this.form.publishId) {
        return;
      }
      this.queryInfoList('', (data) => {
        // 自动处理下拉列表
      });
    },

    // 选择事件处理
    handleInstrumentSelect(item) {
      this.form.instrumentId = item.id;
      this.form.instrumentName = item.name;
    },

    handleComposerSelect(item) {
      this.form.composerId = item.id;
      this.form.composerName = item.name;
    },

    handleCollectionSelect(item) {
      this.form.collectionId = item.id;
      this.form.collectionName = item.name;
    },

    handlePublishSelect(item) {
      this.form.publishId = item.id;
      this.form.publishName = item.name;
      // 清空出版信息
      this.form.publishInfoId = null;
      this.form.publishInfoName = '';
    },

    handleInfoSelect(item) {
      this.form.publishInfoId = item.id;
      this.form.publishInfoName = item.name;
    },

    // 移除原有的handlePublishChange方法，因为已经不需要了

    // ... existing code ...
  }
}
</script>

<style scoped>
.url-container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.pdf-link {
  word-break: break-all;
  margin-bottom: 15px;
  color: #409EFF;
  text-decoration: underline;
}

.url-container .el-button {
  margin-top: 10px;
}

.url-container .el-input {
  margin-right: 10px;
}
</style>
